package com.android.adapter;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public abstract class AbstractDbAdapter {
	
	protected static final String TAG = "ForecastDbAdapter";
    protected DatabaseHelper mDbHelper;
    protected SQLiteDatabase mDb;
    
    private static final String DATABASE_CREATE_PART_NUMBER =
        "CREATE TABLE IF NOT EXISTS part_number (uid text primary key, name text, desc text, " +
        "leadtime numeric, forecast numeric, rop integer, std numeric);";       
    
    private static final String DATABASE_NAME = "forecast";
    protected static final int DATABASE_VERSION = 1;

    protected final Context mCtx;
    
    protected static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE_PART_NUMBER);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS part_number");           
            onCreate(db);
        }
    }
    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public AbstractDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    /**
     * Open or create the routes database.
     * 
     * @return this
     * @throws SQLException if the database could be neither opened or created
     */
    public AbstractDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }
}
